﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using Microsoft.Xna.Framework.Media;
using SMARTMobile.Common;
using SmartMobile.Data;
using SMARTMobile.Models.Local;
using SMARTMobile.WinPhone;
using Microsoft.Phone;
using System.Windows;

namespace SMARTMobile.ViewModels
{
    public class ChupHinhMainViewModel : ViewModelBase
    {
        private bool _isRunningBusyIndicator;
        private string _description;
        private string _diaChi;
        private string _customerCode;
        private bool _isTakePicture = false;
        private BitmapImage _visitImageSource;
        SmartMobileDBContext smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);

        public ChupHinhMainViewModel()
        {
            base.IsBusy = true;
            this.ChupHinhCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteChupHinhCommand
            };

            this.ThoatCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteThoatCommand
            };

            this.LuuCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteLuuCommand
            };

            //if (GlobalInformation.ReportImageTypes == null || !GlobalInformation.ReportImageTypes.Any())
            //{
            GlobalInformation.ReportImageTypes = GetImageType();
            //}

            if (GlobalInformation.ReportImageTypes != null && GlobalInformation.ReportImageTypes.Any())
            {
                IMAGETYPE imageType = GlobalInformation.ReportImageTypes[GlobalInformation.StateImageType];
                if (imageType != null)
                {
                    this.Description = imageType.Description;
                }
            }

            if (GlobalInformation.SelectedTCARCUS != null)
            {
                DiaChi = GlobalInformation.SelectedTCARCUS.Address + ", " + GlobalInformation.SelectedTCARCUS.Street + ", " + GlobalInformation.SelectedTCARCUS.Ward +
                                          ", " + GlobalInformation.SelectedTCARCUS.Provice;
                this.CustomerCode = GlobalInformation.SelectedTCARCUS.Customerkey;
            }
        }

        private List<IMAGETYPE> GetImageType()
        {
            try
            {
                // It will copy from local to iso
                smartMobileContext.CreateIfNotExists();

                // log sql query native on Output window
                smartMobileContext.LogDebug = true;

                return smartMobileContext.IMAGETYPE.ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public BitmapImage base64image(string base64string)
        {
            byte[] fileBytes = Convert.FromBase64String(base64string);

            using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
            {
                ms.Write(fileBytes, 0, fileBytes.Length);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(ms);
                return bitmapImage;
            }
        }

        public string ToBase64String(BitmapImage bmp)
        {
            string base64String = string.Empty;
            ////;
            ////MemoryStream memoryStream = new MemoryStream();
            ////bmp.Save(memoryStream, imageFormat);

            ////memoryStream.Position = 0;
            ////byte[] byteBuffer = memoryStream.ToArray();

            ////memoryStream.Close();

            base64String = Convert.ToBase64String(ConvertToBytes(bmp));
            ////byteBuffer = null;

            return base64String;
        }

        public override void PageLoaded(Uri uri)
        {
            base.PageLoaded(uri);
            base.IsBusy = false;

            if (!this.IsTakePicture)
            {
                if (GlobalInformation.StateImageType < GlobalInformation.ReportImageTypes.Count)
                {
                    // Load image
                    var currentImgCus = (from imgCus in smartMobileContext.IMAGECUSTOMER where imgCus.CustomerKey == GlobalInformation.SelectedTCARCUS.Customerkey && imgCus.Type == GlobalInformation.ReportImageTypes[GlobalInformation.StateImageType].ID select imgCus).FirstOrDefault();
                    if (currentImgCus != null)
                    {
                        this.VisitImageSource = Utilities.ImageUtilities.LoadImageFromIsolatedStorage(currentImgCus.CustomerKey + "~" + GlobalInformation.ReportImageTypes[GlobalInformation.StateImageType].ID + ".Jpeg");
                     }
                    else
                    {
                        this.VisitImageSource = null;
                    }
                }
            }
        }

        public ICommandRoute ChupHinhCommand { get; private set; }
        public ICommandRoute ThoatCommand { get; private set; }

        public ICommandRoute LuuCommand { get; private set; }
        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                base.RaisePropertyChanged("Description");
            }
        }

        public BitmapImage VisitImageSource
        {
            get { return _visitImageSource; }
            set { _visitImageSource = value; base.RaisePropertyChanged("VisitImageSource"); }

        }

        public string DiaChi
        {
            get { return _diaChi; }
            set { _diaChi = value; base.RaisePropertyChanged("DiaChi"); }
        }

        public string CustomerCode
        {
            get { return _customerCode; }
            set { _customerCode = value; base.RaisePropertyChanged("CustomerCode"); }
        }

        public bool IsTakePicture
        {
            get { return _isTakePicture; }
            set { _isTakePicture = value; }
        }

        public void ChangeImage()
        {
            using (var library = new MediaLibrary())
            {
                Picture photoFromLibrary = library.Pictures[library.Pictures.Count - 1];
                BitmapImage latestBitmapImage = new BitmapImage();
                latestBitmapImage.SetSource(photoFromLibrary.GetImage());
                VisitImageSource = latestBitmapImage;
            }
        }

        private void ExecuteChupHinhCommand(object commandParams)
        {
            this.ChupHinhCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("ChupHinhCuaHang");

            //base.ApplicationBar.MenuItems.Clear();

            //this._menuItem1 = new PhoneApplicationBarMenuItem(Localization.AppResources.COMMON_ACTION_SETTING);
            //this._menuItem2 = new PhoneApplicationBarMenuItem(Localization.AppResources.COMMON_ACTION_DATASYNC);

            //base.ApplicationBar.MenuItems.Add(this._menuItem1);
            //base.ApplicationBar.MenuItems.Add(this._menuItem2);
        }

        private void ExecuteThoatCommand(object commandParams)
        {
            if (!this.IsTakePicture)
            {
                MessageBoxResult result = MessageBox.Show("Chưa chụp hình bạn có muốn tiếp tục không?", "Cảnh báo", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    this.ThoatCommand.RaiseCanExecuteChanged(true);
                    return;
                }
            }
            
            this.ThoatCommand.RaiseCanExecuteChanged(true);
            //base.PageNavigation.Navigate("NhapDuLieu");
            base.PageNavigation.Navigate("InputData");
        }
        private void ExecuteLuuCommand(object commandParams)
        {
            try
            {
                // Save current picture
                if (this.IsTakePicture)
                {
                    if (GlobalInformation.ReportImageTypes != null && GlobalInformation.SelectedTCARCUS != null && this.VisitImageSource != null)
                    {
                        var currentImgCus = (from imgCus in smartMobileContext.IMAGECUSTOMER where imgCus.CustomerKey == GlobalInformation.SelectedTCARCUS.Customerkey && imgCus.Type == GlobalInformation.ReportImageTypes[GlobalInformation.StateImageType].ID select imgCus).FirstOrDefault();
                        if (currentImgCus == null)
                        {
                            currentImgCus = new IMAGECUSTOMER();
                            currentImgCus.CustomerKey = GlobalInformation.SelectedTCARCUS.Customerkey;
                            //newImageCustomer.ReportPicture = ConvertToBytes(this.VisitImageSource);
                            currentImgCus.Salespkey = "2";
                            currentImgCus.ReportDate = DateTime.Now.ToString();
                            currentImgCus.Recdate = DateTime.Now.ToString();
                            currentImgCus.Type = GlobalInformation.ReportImageTypes[GlobalInformation.StateImageType].ID;
                            currentImgCus.ID_PK = Guid.NewGuid();

                            // It will copy from local to iso
                            smartMobileContext.CreateIfNotExists();
                            smartMobileContext.IMAGECUSTOMER.InsertOnSubmit(currentImgCus);
                            smartMobileContext.SubmitChanges();
                        }

                        Utilities.ImageUtilities.SaveToJpeg(this.VisitImageSource, GlobalInformation.SelectedTCARCUS.Customerkey + "~" + GlobalInformation.ReportImageTypes[GlobalInformation.StateImageType].ID + ".Jpeg");
                    }
                }
                else
                {
                    MessageBoxResult result = MessageBox.Show("Chưa chụp hình bạn có muốn tiếp tục không?", "Cảnh báo", MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.Cancel)
                    {
                        this.LuuCommand.RaiseCanExecuteChanged(true);
                        return;
                    }
                }

                GlobalInformation.StateImageType += 1;
                if (GlobalInformation.ReportImageTypes != null && GlobalInformation.StateImageType < GlobalInformation.ReportImageTypes.Count)
                {
                    IMAGETYPE imageType = GlobalInformation.ReportImageTypes[GlobalInformation.StateImageType];
                    if (imageType != null)
                    {
                        this.Description = imageType.Description;
                        if (IsTakePicture)
                        {
                            this.VisitImageSource = null;
                        }
                        else
                        {
                            string imageName = GlobalInformation.SelectedTCARCUS.Customerkey + "~" + GlobalInformation.ReportImageTypes[GlobalInformation.StateImageType].ID + ".Jpeg";
                            if (Utilities.ImageUtilities.CheckFileExist(imageName))
                            {
                                this.VisitImageSource = Utilities.ImageUtilities.LoadImageFromIsolatedStorage(imageName);
                            }
                            else
                            {
                                this.VisitImageSource = null;
                            }
                        }
                    }
                }
                else
                {
                    //base.PageNavigation.Navigate("NhapDuLieu");
                    base.PageNavigation.Navigate("InputData");
                }

                this.IsTakePicture = false;
            }
            catch (Exception)
            {
            }

            this.LuuCommand.RaiseCanExecuteChanged(true);
        }

        public byte[] ConvertToBytes(BitmapImage bitmapImage)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                WriteableBitmap btmMap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);

                // write an image into the stream
                btmMap.SaveJpeg(ms, 240, 240, 0, 100);

                return ms.ToArray();
            }
        }

        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        private IMAGECUSTOMER getImageCustomer()
        {
            try
            {
                SmartMobileDBContext smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);

                // It will copy from local to iso
                smartMobileContext.CreateIfNotExists();

                // log sql query native on Output window
                smartMobileContext.LogDebug = true;

                // Query - Same with SQL SERVER Linq
                List<IMAGECUSTOMER> list = new List<IMAGECUSTOMER>();
                list = smartMobileContext.IMAGECUSTOMER.ToList();

                return list.FirstOrDefault(x => x.CustomerKey == GlobalInformation.SelectedTCARCUS.Customerkey && x.Type == GlobalInformation.StateImageType.ToString());
            }
            catch (Exception)
            {
                return null;
            }
        }


        public string ConvertImageToString(WriteableBitmap bitmapImage)
        {
            byte[] byteArray = null;
            using (MemoryStream stream = new MemoryStream())
            {
                ////WriteableBitmap btmMap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
                bitmapImage.SaveJpeg(stream, 240, 240, 0, 100);
                byteArray = stream.ToArray();
            }
            return Convert.ToBase64String(byteArray);
        }

        public WriteableBitmap ConvertStringToImage(string Text)
        {
            byte[] filebytes = Convert.FromBase64String(Text);
            using (Stream memStream = new MemoryStream(filebytes))
            {
                WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);
                return wbimg;
            }

            //using (MemoryStream ms = new MemoryStream(filebytes, 0, filebytes.Length))
            //{
            //    ms.Write(filebytes, 0, filebytes.Length);
            //    BitmapImage image = new BitmapImage();
            //    image.SetSource(ms);
            //    return image;
            //}
        }
    }
}

